package multiagent

import (
	"anders-cli/internal/ai"
	"fmt"
	"strings"
	"time"
)

// BusinessAnalyst 业务分析员Agent
type BusinessAnalyst struct {
	*BaseAgent
}

// NewBusinessAnalyst 创建业务分析员
func NewBusinessAnalyst(backend ai.Backend) *BusinessAnalyst {
	return &BusinessAnalyst{
		BaseAgent: &BaseAgent{
			Name:        "Business_Analyst",
			Role:        "Business Analyst",
			Backend:     backend,
			TaskCounter: 0,
		},
	}
}

// NewBusinessAnalystWithRules 创建带有角色规则的业务分析员
func NewBusinessAnalystWithRules(characterName string, backend ai.Backend) (*BusinessAnalyst, error) {
	baseAgent, err := NewBaseAgentWithRules("Business_Analyst", "analyst", characterName, backend)
	if err != nil {
		return nil, err
	}

	return &BusinessAnalyst{
		BaseAgent: baseAgent,
	}, nil
}

// Process 处理业务分析任务
func (ba *BusinessAnalyst) Process(task string, context map[string]any) (output string, confidence int, feedback string) {
	// 初始化日志以防nil指针
	ba.initLog()

	// 使用角色规则构建基础提示
	basePrompt := ba.RulesContent
	if basePrompt == "" {
		basePrompt = fmt.Sprintf("You are %s, a Business Analyst. Analyze business requirements and provide structured analysis.", ba.Name)
	}

	prompt := fmt.Sprintf(`%s

Task: %s

Please provide:
1. Business Requirements Analysis
2. User Stories (in standard format: "As a [user], I want [functionality] so that [benefit]")
3. Key Business Rules and Constraints
4. Success Criteria and Acceptance Criteria

Keep your analysis focused and actionable.`, basePrompt, task)

	output, err := ba.Backend.Query(prompt, nil)
	if err != nil {
		return fmt.Sprintf("Business analysis failed: %v", err), 20, "Technical error in analysis"
	}

	// 评估置信度
	confidence = ba.evaluateConfidence(output, task)

	// 生成反馈
	feedback = ba.generateFeedback(output, confidence)

	// 更新任务日志
	ba.CurrentLog = &TaskLog{
		TaskID:        ba.generateTaskID(),
		Description:   "Business requirements analysis",
		InputSummary:  fmt.Sprintf("Task: %s", task[:min(50, len(task))]),
		OutputSummary: output[:min(100, len(output))],
		Status:        "completed",
		Confidence:    confidence,
		Feedback:      feedback,
		Timestamp:     time.Now().Unix(),
	}

	return output, confidence, feedback
}

// evaluateConfidence 评估输出置信度
func (ba *BusinessAnalyst) evaluateConfidence(output, task string) int {
	confidence := 70 // 基础置信度

	// 检查是否包含关键业务分析元素
	keyIndicators := []string{"requirements", "user stories", "business rules", "success criteria"}
	matchedIndicators := 0

	for _, indicator := range keyIndicators {
		if strings.Contains(strings.ToLower(output), indicator) {
			matchedIndicators++
		}
	}

	// 根据匹配的指标数量调整置信度
	confidence += matchedIndicators * 5

	// 检查输出长度（太短可能质量不高）
	if len(output) < 100 {
		confidence -= 20
	} else if len(output) > 1000 {
		confidence += 5
	}

	if confidence > 95 {
		confidence = 95
	}
	if confidence < 30 {
		confidence = 30
	}

	return confidence
}

// generateFeedback 生成反馈
func (ba *BusinessAnalyst) generateFeedback(output string, confidence int) string {
	if confidence >= 80 {
		return "Business analysis completed successfully with comprehensive coverage"
	} else if confidence >= 60 {
		return "Business analysis completed with basic coverage, may need refinement"
	} else {
		return "Business analysis may be incomplete, consider additional clarification"
	}
}
